import { createSlice } from "@reduxjs/toolkit";
import axios from "axios";

const billStore = createSlice({
    name:'bill',
    //数据状态
    initialState:{
        billList:[]
    },
    reducers:{
        //同步方法
        setBillList(state,action){
            state.billList = action.payload;
        },
        //同步添加账单方法
        addBill(state,action){
            state.billList.push(action.payload);
        }
    }
})

//结构action
const { setBillList,addBill } = billStore.actions;

//异步请求
const getBillListAsync = ()=>{
    return async (dispatch)=>{
        const res = await axios.get('http://localhost:8007/ka');
        console.log(res,'res')
        dispatch(setBillList(res.data));
    }
}

const addBillList = (data)=>{
    return async (dispatch)=>{
        const res = await axios.post('http://localhost:8007/ka',data);
        console.log(res,'res')
        dispatch(addBill(res.data));
    }
}

export{ getBillListAsync,addBillList };



const reducer = billStore.reducer;

export default reducer;


